﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace Synchros
{
    public partial class FrmCenter : Form
    {
        public FrmCenter()
        {
            InitializeComponent();
        }
        public FrmCenter(string [] strArgs)
        {
            this.strArgs = strArgs;
            InitializeComponent();
        }

        #region 全局变量
        // 启动参数
        private string[] strArgs;
        // 同步配置列表
        List<SyncItem> lstSync = new List<SyncItem>();

        // 工作线程组
        private Thread[] threads;

        // 当前同步的状态
        bool isSync = false;

        /// <summary>
        /// 同步索引等相关变量
        /// </summary>
        SyncIndex idxGroup = new SyncIndex();
        #endregion

        #region 表单事件

        #region 页面加载事件
        private void FrmCenter_Load(object sender, EventArgs e)
        {
            // 检查配置文件
            XmlHelper.CheckConfigExist();

            //绑定事件
            SqlHelper.ShowMessageEvent += new SqlHelper.ShowMessageDelegate(SM);

            // 根据args参数，初始化，比如开机启动后最小化之类的
            if (strArgs != null)
            {
                if (strArgs.Length > 0 && strArgs[0] == "sync=1")
                {
                    SyncStart();
                }
                if (strArgs.Length > 1 && strArgs[1] == "mini=1")
                {
                    this.Hide();//隐藏界面
                    this.ShowInTaskbar = false;//隐藏任务栏
                }
            }
        }
        #endregion

        #region 托盘鼠标点击事件
        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                //已显示则让它显示在最上面
                if (this.Visible)
                {
                    this.Visible = false;
                    this.WindowState = FormWindowState.Minimized;
                    //this.ShowInTaskbar = true;

                    this.TopMost = true;
                    this.TopMost = false;
                }
                else
                {
                    this.Visible = true;
                    this.WindowState = FormWindowState.Normal;
                    this.TopMost = true;
                    this.TopMost = false;
                }
            }
            //else if (e.Button == MouseButtons.Right)
            //{
            //    notifyIcon1.ContextMenu.Show(contextMenuStrip1, new Point(50, 50));
            //    //contextMenuStrip1.Show()
            //}
            //if (this.WindowState == FormWindowState.Minimized)
            //{
            //    this.Hide();
            //    this.notifyIcon1.Visible = true;
            //}
            //this.Show();
            ////this.notifyIcon1.Visible = false;
        }
        #endregion

        #region 配置事件

        //配置转换
        private void tsmiConver_Click(object sender, EventArgs e)
        {
            new FrmConver().Show();
        }
        //连接配置
        private void tsmiServer_Click(object sender, EventArgs e)
        {
            //System.Windows.Forms.DialogResult result = new FrmServer().ShowDialog();
            new FrmServer().Show();
        }
      
        //同步配置
        private void tsmiConfig_Click(object sender, EventArgs e)
        {
            //System.Windows.Forms.DialogResult result = new FrmConfig(!tsbtnStart.Enabled).ShowDialog();
            new FrmConfig(!tsbtnStart.Enabled).Show();
        }
        //软件设置
        private void tsmiSystem_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.DialogResult result = new FrmSystem().ShowDialog();
        }
        private void tsmiLog_Click(object sender, EventArgs e)
        {
            //System.Windows.Forms.DialogResult result = new FrmLogger().ShowDialog();
            new FrmLogger().Show();
        }
        private void tsmiAbout_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.DialogResult result = new FrmGuanyu().ShowDialog();
        }

        private void tsbtnServer_Click(object sender, EventArgs e)
        {
            //System.Windows.Forms.DialogResult result = new FrmServer().ShowDialog();
            new FrmServer().Show();
        }

        private void tsbtnConfig_Click(object sender, EventArgs e)
        {
            //System.Windows.Forms.DialogResult result = new FrmConfig(!tsbtnStart.Enabled).ShowDialog();
            new FrmConfig(!tsbtnStart.Enabled).Show();
        }

        private void tsbtnSystem_Click(object sender, EventArgs e)
        {
            //System.Windows.Forms.DialogResult result = new FrmSystem().ShowDialog();
            new FrmSystem().Show();
        }
        #endregion

        #region 退出事件
        //点击关闭
        private void FrmCenter_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Hide();//隐藏界面
            this.ShowInTaskbar = false;//隐藏任务栏
            e.Cancel = true;//取消事件
        }
        //托盘右键退出
        private void tsmiExit_Click(object sender, EventArgs e)
        {
            if (this.tsbtnClose.Enabled)
            {
                DialogResult result = MessageBox.Show("数据正在同步中,你确定要退出吗？", "", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    this.notifyIcon1.Visible = false;//隐藏托盘图表
                    Environment.Exit(0);//退出系统
                }
            }
            else
            {
                this.notifyIcon1.Visible = false;//隐藏托盘图表
                Environment.Exit(0);//退出系统
            }            
        }
        #endregion

        #region 同步事件(开始,暂停,结束)
        // 开始同步
        private void tsbtnStart_Click(object sender, EventArgs e)
        {
            SyncStart();
        }
        //暂停同步
        private void tsbtnPause_Click(object sender, EventArgs e)
        {
            SyncPause(true);
        }
        // 结束同步
        private void tsbtnClose_Click(object sender, EventArgs e)
        {
            SyncClose();
        }

        #endregion
        
        #region 清空信息
        private void tsbtnClear_Click(object sender, EventArgs e)
        {
            lsbMessage.Items.Clear();
            tsbtnClear.Enabled = false;
        }
        #endregion

        #region 窗体大小改变事件
        private void FrmCenter_SizeChanged(object sender, EventArgs e)
        {
            ////this.lstLog.Location = new System.Drawing.Point(0,toolStrip1.Location.Y + toolStrip1.Height);
            //this.lstLog.Size = new System.Drawing.Size(792, this.Height + (toolStrip1.Location.Y - this.Location.Y));
        }

        private void FrmCenter_Resize(object sender, EventArgs e)
        {

        }
        #endregion

        #endregion

        #region 开始同步
        private void SyncStart()
        {
            //0.x判断是否启动暂停
            if (tsbtnClose.Enabled)
            {
                SyncPause(false); return;
            }

            // 0.界面设置            
            tsbtnStart.Enabled = false;
            tsbtnPause.Enabled = true;
            tsbtnClose.Enabled = true;
            lsbMessage.Items.Clear(); // 清空消息

            // 1.加载配置
            try
            {
                lstSync.Clear();
                XmlHelper.FillSyncConfig(lstSync,true);//只加载需要同步的配置
                if (lstSync.Count < 1)
                {
                    SM("同步退出,没有需要同步的配置...");
                    SyncClose();
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                SyncClose();
                return;
            }

            // 2.根据配置初始化相关变量
            isSync = true;//标示当前是否需要同步
            try
            {
                // 创建线程组，开启同步线程
                threads = new Thread[lstSync.Count];
                // 初始化索引起始值
                idxGroup.InitIndex(lstSync.Count);
                for (int iGroup = 0; iGroup < lstSync.Count; iGroup++)
                {
                    for (int iDbase = 0; iDbase < lstSync[iGroup].SyncDb.Rows.Count; iDbase++)
                    {
                        //设置时间间隔
                        lstSync[iGroup].LastDt = DateTime.Now.AddSeconds(-lstSync[iGroup].Spaced);
                    }
                    // 创建整体同步工作线程
                    threads[iGroup] = new Thread(new ThreadStart(SyncThread));                    
                    //SM("开始同步[{0}]...", lstSync[iGroup].SgName);
                    // 开启此工作线程
                    threads[iGroup].Start(); Thread.Sleep(1000);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                //LogHelper.AddLog(ex.Message);
                return;
            }
        }
        #endregion

        #region 暂停同步
        private void SyncPause(bool isPause)
        {
            if (isPause)
            {
                tsbtnStart.Enabled = true;
                tsbtnPause.Enabled = false;
                for (int i = 0; i < threads.Length; i++)
                {
                    threads[i].Suspend();
                }
            }
            else
            {
                tsbtnStart.Enabled = false;
                tsbtnPause.Enabled = true;
                for (int i = 0; i < threads.Length; i++)
                {
                    threads[i].Resume();
                }
            }
        }
        #endregion

        #region 关闭同步
        private void SyncClose()
        {
            try
            {// 停止所有工作线程    
                if (threads != null)//没有需要同步的配置时
                {
                    foreach (Thread thread in threads)
                    {
                        isSync = false;
                        if (thread.ThreadState == ThreadState.Suspended)
                        {
                            thread.Resume();//让线程自己终止                        
                        }
                        //thread.Abort(); // 中断每个线程
                    }
                }
            }
            catch (Exception ex)
            {
                SM(ex.Message);
            }

            // 界面设置
            tsbtnStart.Enabled = true;
            tsbtnPause.Enabled = false;
            tsbtnClose.Enabled = false;
        }
        #endregion


        #region 同步线程
        private void SyncThread()
        {
            #region 局部变量

            int iLocalGroupIndex = 0;
            idxGroup.NextIndex(ref iLocalGroupIndex);
            SyncItem syncitem = lstSync[iLocalGroupIndex];

            #endregion

            while (isSync)
            {
                try
                {
                    #region 时间间隔
                    // 判读距离上一次同步的时间差是否满足时间间隔
                    if (syncitem.Spaced > (DateTime.Now - syncitem.LastDt).TotalSeconds)
                    {
                        continue;
                    }
                    #endregion

                    SM("开始同步:[{0}]...", syncitem.SgName);
                    {
                        // 执行清理
                        SqlHelper.ClearCdc(syncitem);

                        // 执行同步
                        SqlHelper.SyncData(syncitem);
                    }

                    #region 时间善后
                    //更新最后一次同步时间//syncitem.LastDt = DateTime.Now;
                    syncitem.LastDt = DateTime.Now;

                    SM("同步完成:[{0}],下次同步{1}秒后开始", syncitem.SgName, syncitem.Spaced);
                    //时间延迟
                    Thread.Sleep(100);
                    #endregion
                }
                catch (Exception ex)
                {
                    SM(ex.Message);
                    Thread.Sleep(1000);
                }
                finally
                {
                }
            }
            SM("退出同步:[{0}]", syncitem.SgName);            
        }
        #endregion


        #region 委托 消息 日志

        private delegate void CallbackAddMessage(string format, params object[] args);
        private void SM(string format, params object[] args)
        {
            if (lsbMessage.InvokeRequired)
            {
                BeginInvoke(new CallbackAddMessage(SM), new object[] { format, args });
            }
            else
            {                
                string msg = DateTime.Now.ToString("HH:mm:ss.fff") + " " + string.Format(format, args);                

                #region 日志记录

                LogHelper.AddLog(msg);
                //if (strMsg.Contains("正在加载") || strMsg.Contains("正在配置") || strMsg.Contains("开始"))
                //{
                //    LogHelper.AddLog(strMsg);
                //}
                //else if(strMsg.Contains("同步"))
                //{
                //    LogHelper.AddLog(strMsg);
                //}
                //else
                //{
                //    LogHelper.AddLog(strMsg);
                //}

                #endregion

                #region 消息添加

                if (lsbMessage.Items.Count > 1000)
                {
                    lsbMessage.Items.RemoveAt(1);
                }
                lsbMessage.Items.Add(msg);
                lsbMessage.SelectedIndex = lsbMessage.Items.Count - 1;

                #endregion
            }
        }

        // 绘制行事件
        private void lsbMessage_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index != -1)
            {
                string msg = lsbMessage.Items[e.Index].ToString();

                Brush brush = Brushes.Red;
                if (msg.Contains("开始同步"))//strMsg.Contains("正在加载") || strMsg.Contains("正在配置") || 
                {
                    brush = Brushes.Black;//灰色   
                }
                else if (msg.Contains("同步信息"))
                {
                    brush = Brushes.Blue;
                }
                else if (msg.Contains("起始同步"))
                {
                    brush = Brushes.CornflowerBlue;// BlueViolet;
                }
                else if (msg.Contains("清理信息"))
                {
                    brush = Brushes.CornflowerBlue; // brush = Brushes.PaleVioletRed;
                }
                else if (msg.Contains("无法同步"))
                {
                    brush = Brushes.OrangeRed;   // Brushes.MediumVioletRed;
                }
                else if (msg.Contains("同步完成"))  // || msg.Contains("退出同步")
                {
                    brush = Brushes.Green;
                }
                else if (msg.Contains("是同步的"))
                {

                    brush = Brushes.Gray;
                }
                //else if(strMsg.Contains("发现差异"))
                //{
                //    brush = Brushes.CornflowerBlue;//BlueViolet
                //}
                //else if (strMsg.Contains("同步成功"))
                //{
                //    brush = Brushes.Blue;
                //}
                //else if (strMsg.Contains("同步失败"))
                //{
                //    brush = Brushes.Coral;// Brushes.PaleVioletRed; Brushes.OrangeRed; Brushes.MediumVioletRed;Brushes.
                //}
                else
                {
                    brush = Brushes.Red;
                }
                e.Graphics.DrawString(msg, lsbMessage.Font, brush, e.Bounds);
            }
        }

        #endregion

        #region 时间定时刷新
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (this.tsbtnStart.Enabled)
            {
                toolStripStatusLabel1.Text = DateTime.Now.ToString("HH:mm:ss");//yyyy-MM-dd 
            }
            else
            {
                toolStripStatusLabel1.Text = DateTime.Now.ToString("HH:mm:ss.fff");//yyyy-MM-dd 
            }

            //启用/禁用清空按钮
            if (tsbtnClear.Enabled && lsbMessage.Items.Count == 0)
            {
                tsbtnClear.Enabled = false;
            }
            else if (!tsbtnClear.Enabled && lsbMessage.Items.Count > 0)
            {
                tsbtnClear.Enabled = true;
            }
        }
        #endregion

       
    }
}
